#!/usr/bin/env python
#coding=utf-8

'''
Created on 2009-2-26

@author: zarra
'''


from sqlalchemy import  Column, Integer, String,Unicode,UnicodeText, DateTime,Text, ForeignKey
from sqlalchemy.orm import relation#, backref,eagerload,sessionmaker,scoped_session
from lxml import etree
import json
from model.expr_a._base import Base,expr_a

def getElementByTagName(doc,tagname):
        return doc.xpath("//%s"%tagname)
    
    
class Ryjl(Base):
    __tablename__='expr_ryjl'
    id         = Column('jl_id'  ,String(16),primary_key=True)
    expr_id    = Column('expr_id',String(16),nullable=False)
    patient_id = Column('br_id'  ,String(16),ForeignKey('vw_brxx_all.br_id'))
    
    #patient = relation(Patient, backref=backref('ryjl', order_by=id,uselist=False))
    
    zs       = Column('ryjl_zs',UnicodeText)
    xbs      = Column('ryjl_xbs',UnicodeText)
    jws      = Column('ryjl_jws',UnicodeText)
    grs      = Column('ryjl_grs',UnicodeText)
    hys      = Column('ryjl_hys',UnicodeText)
    jzs      = Column('ryjl_jzs',UnicodeText)
    tgjc     = Column('ryjl_tgjc',UnicodeText)
    zkqk     = Column('ryjl_zkqk',UnicodeText)
    fzjc     = Column('ryjl_fzjc',UnicodeText)
    zd       = Column('ryjl_zd',UnicodeText)
    yjs      = Column('ryjl_yjs',UnicodeText)
    kzzd     = Column('ryjl_kzzd',UnicodeText)    
    provider = Column('ryjl_bscsz',UnicodeText)
    time     = Column('jl_sj',DateTime)
    column_names={
              'zs':'主诉',
              'xbs':'现病史',
              'jws':'既往史',
              'grs':'个人史',
              'hys':'婚姻史',
              'jzs':'家族史',
              'tgjc':'体格检查',
              'zkqk':'专科检查',
              'fzjc':'辅助检查',
              'zd':'初步诊断',
              'yjs':'月经史',
              'provider':'供史者',
              'time':'记录时间',
              'kzzd':'专科诊断',
              'ryjl_zljh':'',
              'ryjl_by1':'',
              'ryjl_by2':'',
              'ryjl_kzzd':'',
              'ryjl_gms':'',
              'ryjl_tw':'',
              'ryjl_mb':'',
              'ryjl_hx':'',
              'ryjl_ssy':'',
              'ryjl_szy':'',           
              }
    column_order=('zs',
              'xbs',
              'jws',
              'grs',
              'hys',
              'jzs',
              'tgjc',
              'zkqk',
              'fzjc',
              'zd',
              'yjs',
              'provider',
              'time',
              'kzzd',
              )  
    def __init__(self):
        pass
    def __repr__(self): 
        return json.dumps(self.__json__())
    def __json__(self):
        result = []
        for item in self.column_order:
            item_value = getattr(self, item)
            if len(item_value)>0:
                value = {'item':item,'item_name':self.column_names[item],'value':item_value}
                result.append(value)
        return {"type":'ryjl',
                "type_name":'入院记录',
                'id':self.id.strip(),
                'content':result}
            
    
class Bcjl(Base):
    __tablename__='expr_bcjl'
    
    name_dictionary=[
             '入院录',
             '首次病程录',
             '新病人主治查房',
             '新病人主任查房',
             '危重主任查房',
             '一般病程记录',
             '主治医师查房',
             '主任医师查房',
             '疑难病人查房',
             '手术记录',
             '阶段小结',
             '术前小结',
             '转科录',
             '24小时入院死亡记录',
             '24小时入院记录',
             '死亡记录',
             '出院记录',
             ]
    
    node_name=[#
               ('bqjj','病情简介'),
               ('mqqk','目前情况'),
               ('zdjzdyj','诊断及诊断依据'),
               ('jbzd','基本诊断'),
               ('zlyz','治疗原则'),
               ('zlgczyzydwt','治疗过程中应注意的问题'),
               #一般病程记录
               ('ybbcjlnr','一般病程记录'),
               #主任查房记录
               ('zrcfjl','主任查房记录'),
               #主治查房记录
               ('zzcfjl','主治查房记录'),
               #术前小节
               ('sqxj_bszy','病史摘要'),
               ('sqxj_sqzd','术前诊断'),
               ('sqxj_sszz','手术指征'),
               ('sqxj_nsssmchfs','拟施手术名称和方法'),
               ('sqxj_mzfs','麻醉方式'),
               ('sqxj_zysx','注意事项'),
               ('sqxj_sqzbqk','术前准备情况'),
               ('sqxj_ssmchfs','手术名称和方法'),
               ('sqxj_sskncxdywhffcs','手术可能出现的意外和防范措施'),
               ('sqxj_zc','职称'),
               #阶段小结
               ('jdxj_ryzd','入院诊断'),
               ('jdxj_mqzd','目前诊断'),
               ('jdxj_zyjg','住院经过'),
               ('jdxj_zlyz','治疗原则'),
               ]
    
    id         = Column('jl_id'  ,String(16),primary_key=True)
    expr_id    = Column('expr_id',String(16),nullable=False)
    patient_id = Column('br_id'  ,String(16))
    jl_sj      = Column('jl_sj',DateTime)
    sign       = Column('cjr_xm',String(16))
    bl_id      = Column('bl_id',String(16),ForeignKey('expr_bl.bl_id'))
    content    = Column('bcjl_zw',Unicode)#正文
    is_del     = Column('is_del',Integer,nullable=False)
    qm1        = Column('qm1',Unicode(16))
    qm2        = Column('qm2',Unicode(16))
    qm3        = Column('qm3',Unicode(16))
    bl = relation("Bl", order_by="Bl.id")
    
    def __init__(self):
        self.content_doc =None
    
    def __repr__(self): 
        return json.dumps(self.__json__())
    
    def __getattr__(self,name):
        if name =='content_doc':
            self.content_doc = etree.fromstring(self.content)
            return self.content_doc
        if self.content_doc == None:
            self.content_doc = etree.fromstring(self.content)
        elements = getElementByTagName(self.content_doc, name)
        if len(elements)>0:
            
            return elements[0].text
        else:
            raise AttributeError(name)
    def __json__(self):
        result = []
        doc  = etree.fromstring(self.bl.sz)
        elements=getElementByTagName(doc, 'blzd')
        for e in elements:
            key =''
            title=''
            value=''
            not_null = False
            for element in e.iter():
                k,v = element.tag, element.text
                if k =='zd_mc':
                    title=v
                elif k=='zd_mc_sx':
                    key=v
                elif k=='not_null':
                    not_null=bool(int(v))
            #print key,title,not_null,value
            
            value=getattr(self, key)
            if isinstance(value,basestring):
                value = value.strip()
            #print title,value,len(value)
            if value!=None and len(value)>0:
                result.append({'item':key,'item_name':title,'value':value})   
        return {"type":self.bl.name_id.strip(),
                "type_name":self.bl.name.strip(),
                'id':self.id.strip(),
                'content':result}
    
    
        
class Bl(Base):
    __tablename__='expr_bl'
    
    id=Column('bl_id',String(16),primary_key=True)
    
    name=Column('bl_mc',Unicode(32),nullable=False)
    name_id=Column('bl_mc_sx',Unicode(32),nullable=False)
    
    type_id = Column('lx_mc_sx',String(32),nullable=False)
    type = Column('lx_mc',Unicode(32),nullable=False)
    
    template = Column('bl_ucl',UnicodeText,nullable=False)
    is_del   = Column('is_del',Integer,nullable=False)
    sz       = Column('bl_sz',UnicodeText)
    
    def __repr__(self):
        return self.name.strip()
    
    
if __name__ == '__main__':
    s=expr_a()
    result =s.query(Bcjl).filter(Bcjl.bl_id == '1400000922').first()
    #print result.content
    print result
    
    
#def find_ryjl_by_expr_id(expr_id):
#    records=expr_a().query(Ryjl).filter(Ryjl.expr_id == expr_id).order_by(Ryjl.time)
#    return records.all()
#
#def find_bcjl_by_expr_id(expr_id):
#    records=expr_a().query(Bcjl).filter(Bcjl.expr_id == expr_id).order_by(Bcjl.time)
#    return records.all()
#
#def find_ryjl_by_id(id):
#    records=expr_a().query(Ryjl).filter(Ryjl.id == id).order_by(Ryjl.time)
#    return records.all()
#
#def find_bcjl_by_id(id):
#    records=expr_a().query(Bcjl).filter(Bcjl.id == id).order_by(Bcjl.time)
#    return records.all()
#
#def find_patients_by_department(b_id,is_in_hospital=True):
#    q=expr_a().query(Patient).filter(Patient.department == b_id).order_by(Patient.bed)
#    if is_in_hospital:
#        return q.filter(Patient.flag == '在院').all()
#    else:
#        return q.all() 
#
#def find_patient_by_id(expr_id): 
#    q=expr_a().query(Patient).filter(Patient.expr_id == expr_id)
#    return q.first()
#
#def list_bl(expr_id):
#    
#    ryjl=find_ryjl_by_expr_id(expr_id)
#    if len(ryjl) > 0:
#        ryjl=ryjl[0]
#    else:
#        ryjl=None
#    
#    bcjls={}
#    for bcjl in find_bcjl_by_expr_id(expr_id):
#        name=str(bcjl.get_bl_name()).strip()
#        if name  not in bcjls:
#            bcjls[name]={}
#        #bcjls[name].append(bcjl)
#        doc=etree.fromstring(bcjl.content)
#        try:
#            for k,v in Bcjl.node_name.items():
#                
#             nodes=getElementByTagName(doc, 'bcjl_%s'%(k))
#             if len(nodes)>0:
#                 text=nodes[0].text
#                 bcjls[name][v]=text
#        except :pass
#        #print bcjls[name]
#    return ryjl,bcjls